import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: fzykd
 * Date: 2022-11-09
 * Time: 11:30
 */

public class TcpEchoServer {
    //网络编程前提 TCP的服务器和客户端不一样
    private ServerSocket socket = null;

    //构造方法 指定服务器的端口号
    public TcpEchoServer(int port) throws IOException {
        socket = new ServerSocket(port);
    }

    //启动服务器
    public void start() throws IOException {
        System.out.println("启动服务器！");
        while (true){
            //TCP是有连接的 不能一上来就接收数据 而是建立连接
            //accept就是接电话的功能 返回的是一个Socket对象
            Socket clientSocket = socket.accept();
            //剩下的事情交给 这个函数来处理
            processConnection(clientSocket);
        }
    }

    private void processConnection(Socket clientSocket) {
        //是哪一个客户端建立的连接
        System.out.printf("[%s:%d] 客户端建立连接!\n",clientSocket.getInetAddress().toString(),clientSocket.getPort());
        //之后 处理请求和相应
        try(InputStream inputStream = clientSocket.getInputStream()){
            try(OutputStream outputStream = clientSocket.getOutputStream()){
                //循环的处理 每一个请求 分别返回相应 Scanner接收处理更加方便 也可以使用原始的读写文件方法
                Scanner scanner = new Scanner(inputStream);
                while (true){
                    //1.读取请求 表示是没有下一条信息
                    if (!scanner.hasNext()){
                        System.out.printf("[%s:%d] 客户端断开连接!\n",clientSocket.getInetAddress().toString(),clientSocket.getPort());
                        break;
                    }
                    //接收传来的数据
                    String request = scanner.next();
                    //根据请求计算相应
                    String response = process(request);
                    //把响应在返回给客户端
                    PrintWriter printWriter = new PrintWriter(outputStream);
                    printWriter.println(response);
                    //刷新缓冲区
                    printWriter.flush();

                    System.out.printf("[%S:%d] req:%s,resp:%s\n",clientSocket.getInetAddress().toString(),
                            clientSocket.getPort(),request,response);
            }
        }
    }catch (IOException e){
            e.printStackTrace();
        }

}

    private String process(String request) {
        return request;
    }


    public static void main(String[] args) throws IOException {
        TcpEchoServer server = new TcpEchoServer(9090);
        server.start();
    }
}
